﻿#include <QPainter>
#include <QPen>

#include "CPlcItemSpace.h"

CPlcItemSpace::CPlcItemSpace(const QRectF &rect,
                             const int8_t type,
                             const QString &str,
                             IPlcBaseItem *parent)
    : IPlcBaseItem(parent)
{
    mVariableNum  = str;
    mSelectActive = false;
    mSwitchOn     = false;
    mType         = type;
    mBranch       = NULL;
    setRect(rect);
}

CPlcItemSpace::~CPlcItemSpace()
{
    //如果当前为选中状态
    if (mSelectActive) setOnlySelectItem(NULL);
}

QRectF CPlcItemSpace::getRect()
{
    return mRect;
}

void CPlcItemSpace::setRect(const QRectF &rect)
{
    if (mRect == rect) return;
    //准备调整几何边界
    prepareGeometryChange();
    mRect         = rect;
    mBoundingRect = QRectF();
    // 缩放比例
    mdScale = mRect.width() / 100.0;
    //重绘
    update();
}

IPlcBaseItem *CPlcItemSpace::getBranch()
{
    return mBranch;
}

void CPlcItemSpace::setBranch(IPlcBaseItem *item)
{
    mBranch = item;
}

void CPlcItemSpace::deleteBranch()
{
    mBranch = NULL;
}

void CPlcItemSpace::setSelectActive(bool status)
{
    //复位之前选中的图元
    IPlcBaseItem *item = getOnlySelectItem();
    if (this != item)
    {
        if (item != NULL) item->setSelectActive(false);
    }

    if (mSelectActive == status) return;

    mSelectActive = status;
    status ? setOnlySelectItem(this) : setOnlySelectItem(NULL);
    //重绘图元
    update();
}

int8_t CPlcItemSpace::getItemType()
{
    return mType;
}

void CPlcItemSpace::setItemType(int8_t type)
{
    if (mType == type) return;
    mType = type;
    update();
}

QRectF CPlcItemSpace::boundingRect() const
{
    if (mBoundingRect.isNull()) mBoundingRect = mRect;

    return mBoundingRect;
}

void CPlcItemSpace::paint(QPainter *painter,
                          const QStyleOptionGraphicsItem *option,
                          QWidget *widget)
{
    Q_UNUSED(option);
    Q_UNUSED(widget);

    // 设置反走样
    painter->setRenderHint(QPainter::Antialiasing, true);
    painter->setRenderHint(QPainter::TextAntialiasing, true);

    //绘制选中状态
    if (mSelectActive)
    {
        QPen pen;
        //设置画笔样式为虚线
        pen.setStyle(Qt::DashLine);
        pen.setWidth(1);         //线宽1
        pen.setBrush(Qt::red);   //颜色蓝色

        painter->setPen(pen);
        painter->drawRect(mRect);   //画矩形
    }
}

bool CPlcItemSpace::getSelectActiveEnb()
{
    return true;
}

bool CPlcItemSpace::getSelectActive()
{
    return mSelectActive;
}
